package fr.loof.fonzie.parsers;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NamedQuery;
import javax.persistence.Query;

import fr.loof.fonzie.PersistenceQuery;

/**
 * @author <a href="nicolas@apache.org">Nicolas De Loof</a>
 */
public class NamedPersistenceQuery
    implements PersistenceQuery
{

    private String namedQuery;

    private Class entity;

    private List<String> parameters = new LinkedList<String>();

    private String jpql;

    /**
     * @param entityClass
     * @param namedQuery
     */
    public NamedPersistenceQuery( Class entityClass, NamedQuery namedQuery )
    {
        this.entity = entityClass;
        this.namedQuery = namedQuery.name();
        jpql = namedQuery.query();
        int i = 0;
        while ( ( i = jpql.indexOf( ":", i + 1 ) ) >= 0 )
        {
            int j = i + 1;
            while ( Character.isJavaIdentifierPart( jpql.charAt( j ) ) )
            {
                j++;
                if ( j >= jpql.length() )
                {
                    break;
                }
            }
            String parameter = jpql.substring( i + 1, j );
            if ( !parameters.contains( parameter ) )
            {
                parameters.add( parameter );
            }
        }
    }

    /**
     * {@inheritDoc}
     * 
     * @see fr.loof.fonzie.PersistenceQuery#createQuery(javax.persistence.EntityManager)
     */
    public Query createQuery( EntityManager entityManager )
    {
        return entityManager.createNamedQuery( namedQuery );
    }

    /**
     * {@inheritDoc}
     * 
     * @see fr.loof.fonzie.PersistenceQuery#getEntity()
     */
    public Class getEntity()
    {
        return entity;
    }

    /**
     * {@inheritDoc}
     * 
     * @see fr.loof.fonzie.PersistenceQuery#parameters()
     */
    public Iterator<String> parameters()
    {
        return parameters.iterator();
    }

    public String toString()
    {
        return jpql;
    }
}
